/*************************************************************************
 * File Name:    Merge_Two_Sorted_Lists.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/17 23:14:39
 * 
 * Description:  
 |-----------------------------------------------------------------------
 | Problem: Merge Two Sorted Lists
 |
 | Merge two sorted linked lists and return it as a new list.
 | The new list should be made by splicing together the nodes of the first two lists.
 |-----------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
    {
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        
        ListNode *head, *tail;
        
        if (l1->val < l2->val) {
            head = l1;
            l1 = l1->next;
        } else {
            head = l2;
            l2 = l2->next;
        }
        tail = head;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val > l2->val) {
                tail->next = l2;
                l2 = l2->next;
            } else {
                tail->next = l1;
                l1 = l1->next;
            }
            tail = tail->next;
        }
        if (l1 != NULL) tail->next = l1;
        if (l2 != NULL) tail->next = l2;
        return head;
    }
};

